//
//  SSDKAliSDK.m
//  SDK_Ali
//
//  Created by 涂俊 on 2018/8/1.
//  Copyright © 2018年 wyht. All rights reserved.
//

#import "SSDKAliSDK.h"
#import "YCSuperSDK/SSDKDelegateWrapper.h"
#import "YCSuperSDK/SSDKHttpUtil.h"
#import "YCSuperSDK/SSDKDataKeys.h"
#import "YCSuperSDK/SSDKEnum.h"
#import "YCSuperSDK/SSDKErrorInfo.h"
#import "YCSuperSDK/SSDKHttpUtil.h"
#import "YCSuperSDK/SSDKEventManager.h"
#import "YCSuperSDK/SSDKEventKeys.h"
#import "YCSuperSDK/SSDKCheckUtil.h"
#import "YCSuperSDK/SSDKUserManager.h"
#import "YCSuperSDK/SSDKDataKeys.h"
#import "YCSuperSDK/SuperSDKInst.h"
#import "SSDKPluginDeviceUtil.h"

#import "NineGameSDK/G9SDKGameInfo.h"
#import "NineGameSDK/G9SDK.h"
#import "NineGameSDK/G9SDKOrder.h"
#import "NineGameSDK/G9SDKParam.h"
#import "NineGameSDK/G9SDKError.h"
#import "NineGameSDK/G9SDKIAPManager.h"

@interface SSDKAliSDK () <G9SDKDelegate, G9SDKIAPManagerDelegate>
@end

@implementation SSDKAliSDK

{
    NSString *callbackUrl;
}


static NSString *KEY_GAME_ID=@"game_id";
static NSString *KEY_APP_KEY=@"app_key";
static NSString *KEY_PAY_CALLBACK=@"callback_url";

-(void) initInfo {
    [SSDKEventManager addObsver:self selector:@selector(initSDK) name:EVENT_INIT object:nil className:@"SSDKAliSDK"];
    [SSDKEventManager addObsver:self selector:@selector(login) name:EVENT_LOGIN object:nil className:@"SSDKAliSDK"];
    [SSDKEventManager addObsver:self selector:@selector(pay:) name:EVENT_PAY object:nil className:@"SSDKAliSDK"];
    [SSDKEventManager addObsver:self selector:@selector(enterPlatform) name:EVENT_ENTERPLATFORM object:nil className:@"SSDKAliSDK"];
    [SSDKEventManager addObsver:self selector:@selector(submitData:) name:EVENT_SUBMITDATA object:nil className:@"SSDKAliSDK"];
}

#pragma mark - AliSDK要求重写的生命周期函数
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary* )options {
    return [[G9SDK sharedInstance] handleUrl:url];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [[G9SDK sharedInstance] handleUrl:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [[G9SDK sharedInstance] handleUrl:url];
}


#pragma mark - AliSDK需要调用的API
- (void) initSDK {
    NSDictionary *data = [[NSBundle mainBundle] infoDictionary];
    NSDictionary *config = [data objectForKey:@"SSDKConfig"];
    NSDictionary *sdkParameters = [config objectForKey:@"SDKParameters"];
    if(sdkParameters==nil) {
        SSDKErrorInfo *error = [[SSDKErrorInfo alloc] init];
        [error setError:@"GET_SDKCONFIG_FAILED" withCode:GET_SDKCONFIG_FAILED];
        [SSDKUserDelegateWrapper initFail:error];
        return;
    }
    // 支付回调地址必须配置，否则会支付掉单
    callbackUrl = [sdkParameters valueForKey:KEY_PAY_CALLBACK];
    if (callbackUrl == nil || callbackUrl.length == 0) {
        SSDKErrorInfo *error = [[SSDKErrorInfo alloc] init];
        [error setError:@"callback_url is null" withCode:LOCAL_CONFIG_ERROR];
        [SSDKUserDelegateWrapper initFail:error];
        return;
    }
    
    // 添加对sdk的监听
    [G9SDK sharedInstance].delegate = self;
    [G9SDKIAPManager sharedManager].delegate = self;
    
    
    [SSDKPluginDeviceUtil requestIDFA:^(NSString *idfa) {
        // 阿里SDK初始化
        G9SDKGameInfo *gameInfo = [[G9SDKGameInfo alloc] init];
        gameInfo.gameId = [[sdkParameters valueForKey:KEY_GAME_ID] integerValue];
        gameInfo.appKey = [sdkParameters valueForKey:KEY_APP_KEY];
        gameInfo.orientation = G9SDKGameInfoOrientationHorizon;
        gameInfo.gameType = G9SDKGameInfoGameTypeOnline;
        gameInfo.idfa = idfa;
        // 在ui线程调用初始化方法
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"G9初始化调用1");
            [[G9SDK sharedInstance] initSDKWithGameInfo:gameInfo];
            NSLog(@"G9初始化调用2");
        });
    }];
    
}

- (void) login {
    //登录
    dispatch_async(dispatch_get_main_queue(), ^{
        [[G9SDK sharedInstance] login];
    });
}

-(void) pay:(NSNotification*) notification {
    if ([[SSDKUserManager getInstance] curUserInfo] == nil) {
        SSDKErrorInfo *error = [[SSDKErrorInfo alloc] initWithError:@"SDK_PAY_FAIL" errorNo:SDK_PAY_FAIL errorMsg:@"抱歉，请先登录"];
        [SSDKPayDelegateWrapper payFail:error];
        return;
    }
    NSString *uid = [[[SSDKUserManager getInstance] curUserInfo] sdkUid];
    if (uid == nil || uid.length == 0) {
        SSDKErrorInfo *error = [[SSDKErrorInfo alloc] initWithError:@"SDK_PAY_FAIL" errorNo:SDK_PAY_FAIL errorMsg:@"抱歉，请先登录"];
        [SSDKPayDelegateWrapper payFail:error];
        return;
    }
    // 创建SuperSDK订单，然后调用g9支付
    SSDKPaymentData *paymentData=[[notification object] objectForKey:SSDK_E_PAYINFO];
    [SSDKPayInfoUtil postWithData:paymentData extra:paymentData.extra httpDelegate:^(SSDKBaseResData *resData) {
        SSDKFWPayInfo *payInfo = [[SSDKFWPayInfo alloc] initWithPayInfo:resData];
        SSDKAppPayInfo *appPayInfo = [[SSDKAppPayInfo alloc] initWithFWPayInfo:payInfo];
        if ([appPayInfo isOk]) {
            G9SDKPurchaseInfo *g9Order = [[G9SDKPurchaseInfo alloc] init];
            g9Order.orderId = payInfo.orderId;
            g9Order.currency = payInfo.currencyType;
            g9Order.prdName = payInfo.productName;
            g9Order.orderAmt = [NSString stringWithFormat:@"%f", payInfo.orderAmount];
            g9Order.iapPayCallbackURL = self->callbackUrl;
            // 订单附加信息:supersdk的OrderId,渠道透传给服务器
            g9Order.attachInfo = [appPayInfo orderId];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[G9SDKIAPManager sharedManager] purchaseWithProductIdentifier:payInfo.productId
                                                                  purchaseInfo:g9Order
                                                                   stateUpdate:^(G9SDKPurchaseState state) {
                    NSLog(@"G9支付当前状态:%lu", (unsigned long)state);
                } success:^(G9SDKOrder *order) {
                    NSLog(@"G9支付成功block:orderId=%@,appleId=%@", order.orderId, order.originalTransId);
                    [self purchaseDidSuccessWithResult:order];
                } failure:^(NSError *error, SKPaymentTransaction *transaction) {
                    NSLog(@"G9支付失败block:error=%@", error);
                    [self purchaseDidFailureWithError:error];
                }];
            });
        } else {
            SSDKErrorInfo *error = [[SSDKErrorInfo alloc] initWithError:@"SDK_PAY_FAIL" errorNo:GET_ORDERID_ERROR errorMsg:[resData error]];
            [SSDKPayDelegateWrapper payFail:error];
        }
    }];
}


//提交数据接口
-(void) submitData:(NSNotification*) notification {
    G9SDKRoleInfo *roleInfo = nil;
    if([[[notification object] objectForKey:SUBMIT_EXT] isEqualToString:SUBMIT_CREATE_ROLE_EVENT]) {
        NSLog(@"G9上报:创建角色");
        roleInfo = [[G9SDKRoleInfo alloc] init];
        roleInfo.opportunityType = G9SDKRoleEventCreate;
    } else if([[[notification object] objectForKey:SUBMIT_EXT] isEqualToString:SUBMIT_LOGIN_EVENT]) {
        NSLog(@"G9上报:角色进入游戏");
        roleInfo = [[G9SDKRoleInfo alloc] init];
        roleInfo.opportunityType = G9SDKRoleEventEnterGame;
    } else if([[[notification object] objectForKey:SUBMIT_EXT] isEqualToString:SUBMIT_LEVEL_UP_EVENT]) {
        NSLog(@"G9上报:角色升级");
        roleInfo = [[G9SDKRoleInfo alloc] init];
        roleInfo.opportunityType = G9SDKRoleEventLevelUpdate;
    } else if([[[notification object] objectForKey:SUBMIT_EXT] isEqualToString:SUBMIT_EXIT_EVENT] ||
              [[[notification object] objectForKey:SUBMIT_EXT] isEqualToString:SUBMIT_LOGOUT_EVENT]) {
        NSLog(@"G9上报:角色退出");
        roleInfo = [[G9SDKRoleInfo alloc] init];
        roleInfo.opportunityType = G9SDKRoleEventExit;
    }
    if (roleInfo != nil) {
        roleInfo.roleId = [[notification object] objectForKey:SUBMIT_ROLE_ID];
        roleInfo.roleName = [[notification object] objectForKey:SUBMIT_ROLE_NAME];
        roleInfo.roleLevel = [[notification object] objectForKey:SUBMIT_ROLE_LEVEL];
        roleInfo.zoneId = [[notification object] objectForKey:SUBMIT_ZONE_ID];
        roleInfo.zoneName = [[notification object] objectForKey:SUBMIT_ZONE_NAME];
        [[G9SDK sharedInstance] setRoleInfo:roleInfo];
    }
}

// 客服中心
- (void) enterPlatform {
    NSLog(@"G9进入客服中心");
    [[G9SDK sharedInstance] showCustomerServiceWebView];
    [SSDKUserDelegateWrapper platformEnter];
}

#pragma mark - AliSDK delegate
/**
 *  成功初始化的回调
 */
- (void)g9_SDKDidFinishInit {
    NSLog(@"G9初始化成功");
    [SSDKUserDelegateWrapper initSuccess];
    
    NSNumber *isBreak = [G9SDKParam valueForKey:@"osjbk"];
    if ([isBreak boolValue]) {
        // 设备越狱，记录下来，会在请求接口时上报给服务器端
        [[SuperSDKInst getInstance] setDeviceBreak];
    }
}

/**
 *  初始化失败的回调，可以通过error.errMessage查看具体错误提示
 */
- (void)g9_SDKFailInit:(G9SDKError *)error {
    NSLog(@"G9登录失败:error=%@", error.errorMessage);
    SSDKErrorInfo *err = [[SSDKErrorInfo alloc] initWithError:@"SDK_INIT_FAILED"
                                                      errorNo:SDK_INIT_FAILED
                                                     errorMsg:error.errorMessage];
    [SSDKUserDelegateWrapper initFail:err];
}

/**
 *  登录成功的回调，会返回sid，如果是单机的离线试玩，则sid为nil，通过服务器对接的方式拿sid换取用户信息
 */
- (void)g9_SDKLoginSuccessWithSid:(NSString *)sid {
    NSLog(@"G9登录成功:sid=%@", sid);
    dispatch_async(dispatch_get_main_queue(), ^{
        [SSDKCheckUtil checkUserLoginSuccessState:@"" accessToken:sid refreshToken:@"" extra:nil];
    });
}

/**
 *  登录失败
 */
- (void)g9_SDKLoginFail:(G9SDKError *)error {
    NSLog(@"G9登录失败:error=%@", error.errorMessage);
    SSDKErrorInfo *err = [[SSDKErrorInfo alloc] initWithError:@"SDK_LOGIN_FAILED"
                                                      errorNo:SDK_LOGIN_FAILED
                                                     errorMsg:error.errorMessage];
    [SSDKUserDelegateWrapper loginFail:err];
}

/**
 *  SDK 已经登出（防沉迷时会触发登出，回到登录界面）
 */
- (void)g9_SDKDidLogout {
    NSLog(@"G9登出完成");
    [SSDKUserDelegateWrapper logoutSuccess];
}

// 支付失败回调
- (void)purchaseDidFailureWithError:(NSError *)error {
    NSLog(@"G9支付失败:error=%@", error);
    SSDKErrorInfo *sdkerror = [[SSDKErrorInfo alloc] initWithError:@"SDK_PAY_FAIL"
                                                           errorNo:SDK_PAY_FAIL
                                                          errorMsg:[error localizedDescription]];
    [SSDKPayDelegateWrapper payFail:sdkerror];
}

// 支付成功回调
- (void)purchaseDidSuccessWithResult:(G9SDKOrder *)product {
    NSLog(@"G9支付成功:orderId=%@,appleId=%@", product.orderId, product.originalTransId);
    if (product.orderId == nil || product.orderId.length == 0) {
        NSLog(@"G9支付成功,但没有订单号，不进行checkOrder。orderId=%@,appleId=%@", product.orderId, product.originalTransId);
        return;
    }
    SSDKAppPayInfo *appPayInfo=[[SSDKAppPayInfo alloc] init];
    [appPayInfo setOrderId:product.orderId];
    [SSDKCheckUtil checkPaySuccessState:appPayInfo extraData:nil];
}

- (void)restoreCompletedTransactionsFailedWithError:(NSError *)error {
    NSLog(@"G9支付restore操作出错:error=%@", error);
}

- (void)restoreCompletedTransactionsFinished {
    NSLog(@"G9支付所有可restore的交易处理完成");
}

- (void)initialIAPManagerFailed:(NSError *)error {
    NSLog(@"G9支付IAP初始化失败");
}


@end
